package com.sophialex.health.record.views.baseinfo;

import java.util.Calendar;
import java.util.List;

import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Text;

import com.sophia.common.xmlbean.pojo.PersonHistoryXMLPojo;
import com.sophia.common.xmlbean.util.PojoXMLUtil;
import com.sophia.dict.vo.DictCode;
import com.sophialex.health.common.platform.SuperContext;
import com.sophialex.health.common.platform.pojo.Geography;
import com.sophialex.health.common.platform.util.CustomGenerator;
import com.sophialex.health.person.vo.HrPerson;
import com.sophialex.health.person.vo.PersonHistory;
import com.sophialex.health.record.Messages;
import com.sophialex.health.record.common.bind.CheckboxBindingUtil;
import com.sophialex.health.record.common.bind.ListPathCheckBinder;
import com.sophialex.health.record.common.util.ControlsCascader;
import com.sophialex.health.record.common.util.DataSource;
import com.sophialex.health.record.common.util.EventType;
import com.sophialex.health.record.common.util.HealthRecordListenerRegister;
import com.sophialex.health.record.common.util.TextCascade;
import com.sophialex.health.record.common.utils.CommonUtils;
import com.sophialex.health.record.common.validate.TextVerifyListener;
import com.sophialex.health.record.dialog.HrPersonMemberSelectDlg;
import com.sophialex.health.record.dialog.QuackAddPersonDialog;
import com.sophialex.health.record.ui.baseinfo.PersonBaseInfoUI;
import com.sophialex.health.record.views.children.ChildRenRegisterView;
import com.sophialex.health.record.views.children.ChildrenCheckView;
import com.sophialex.health.record.views.children.InfantHealthView;
import com.sophialex.health.record.views.pregnant.AntenatalreView;
import com.sophialex.health.record.views.pregnant.Postpartum42DayCheckView;
import com.sophialex.health.record.views.pregnant.PostpartumView;
import com.sophialex.health.record.views.pregnant.PregnantRecordView;
import com.sophialex.health.record.views.visits.DiabetesVisitsView;
import com.sophialex.health.record.views.visits.HypertensionVisitView;
import com.sophialex.health.record.views.visits.SchizophreniaVisitsView;
import com.sophialex.health.record.views.visits.TuberculosisVisits1View;
import com.sophialex.health.system.frame.dialog.DialogManager;
import com.sophialex.health.system.frame.util.ViewUitl;

public class PersonBaseInfoView extends PersonBaseInfoUI implements IPropertyChangeListener{

	public static final String ID = "com.sophialex.health.record.views.baseinfo.PersonBaseInfoView"; //$NON-NLS-1$

	private PersonHistory curHistory = new PersonHistory();

	// private enum OperationState {
	// EDIT, ADD
	// }// doSave会用
	//
	// private OperationState opState = OperationState.ADD;

	// 记录当前tab
	private enum Tab {
		PERSON, HISTORY
	}

	private Tab curTab = Tab.PERSON;// 初始时为基本信息页

	// 记录各tab的工具栏状态
	private PersonBaseInfoViewState curPersonViewState = PersonBaseInfoViewState.ADD_VIEW;

	private PersonBaseInfoViewState curHisViewState = PersonBaseInfoViewState.ADD_VIEW;

	Long curPersonIDofHisTab = 0L;

	public PersonBaseInfoView() {
		// initBean();
		HealthRecordListenerRegister.getInstance().addPropertyChangeListener(this);

	}

	public void createPartControl(Composite parent) {
		super.createPartControl(parent);
		setActionControl();
		initCheckBox();
		ap.process();
		selectHanZu();// 默认选择汉族
		initCombo();
		cascadeMZOther();
		cascadeHistoryCtls();

		ap.updateModel();


	}

	private void cascadeHistoryCtls() {

		// 选“有”的时候后面控件才可用
		ControlsCascader.comboCascade(comboSS, new Control[] { dtSSSJ1, dtSSSJ2, txtSSMC1, txtSSMC2 }, "codeNum", "1", true);
		ControlsCascader.comboCascade(comboWS, new Control[] { dtWSSJ1, dtWSSJ2, txtWSMC1, txtWSMC2 }, "codeNum", "1", true);
		ControlsCascader.comboCascade(comboSX, new Control[] { dtSXSJ1, dtSXSJ2, txtSXYY1, txtSXYY2 }, "codeNum", "1", true);
		ControlsCascader.comboCascade(comboZY, new Control[] { txtZYYY1, txtZYYY2, txtZYYY3, dtRYSJ1, dtRYSJ2, dtRYSJ3, dtCYSJ1, dtCYSJ2, dtCYSJ3, txtYLJGMC1,
				txtYLJGMC2, txtYLJGMC3 }, "codeNum", "1", true);

		// 绝经
		ControlsCascader.comboCascade(cmbNXJJ, new Control[] { txtNXJJNL }, "codeNum", "101001", true);

		// 家族史其他
		new CheckboxBindingUtil().bindTextState(chkZFMQT, txtZFMQT, true);
		new CheckboxBindingUtil().bindTextState(chkWZFMQT, txtWZFMQT, true);
		new CheckboxBindingUtil().bindTextState(chkFQQT, txtFQQT, true);
		new CheckboxBindingUtil().bindTextState(chkMQQT, txtMQQT, true);
		new CheckboxBindingUtil().bindTextState(chkXDJMQT, txtXDJMQT, true);
		new CheckboxBindingUtil().bindTextState(chkZNQT, txtZNQT, true);

		// 遗传病史
		ControlsCascader.comboCascade(cmbYCBSYW, new Control[] { txtJBMC }, "codeNum", "1", true);

		// 残疾有无互斥
		mutexDeformity();

		// 残疾其他
		new CheckboxBindingUtil().bindTextState(chkQTCJ, txtQTCJ, true);
	}

	private void mutexDeformity() {

		final Button[] chks = new Button[] { chkTLCJ, chkYYCJ, chkZTCJ, chkZLCJ, chkJSCJ, chkQTCJ };
		chkWCJ.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				if(chkWCJ.getSelection()) {
					for(Button b : chks) {
						b.setSelection(false);
						txtQTCJ.setText("");
						txtQTCJ.setEnabled(false);
					}
				}
			}

		});

		for(final Button b : chks) {
			b.addSelectionListener(new SelectionAdapter() {

				@Override
				public void widgetSelected(SelectionEvent e) {
					if(b.getSelection()) {
						chkWCJ.setSelection(false);

					}
				}

			});
		}
		// ap.updateModel();
	}

	private void initCheckBox() {
		// 绑定过敏史
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkZJMZJGM, chkDWMFGM, chkKSMGM, chkGJLSGGM, chkSNHCGM, chkJDGM, chkYJBKLSPGM, chkDGM,
				chkNNGM, chkDKDGRGM, chkHFGM, chkQTGM }, personHistory, "allergicHistory.value", null, true);

		// //家族史
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkZFMGXY, chkZFMTNB, chkZFMGXB, chkZFMEXZL, chkZFMGMZ, chkZFMJSFL, chkZFMNZZ, chkZFMJHB,
				chkZFMGY, chkZFMXTJX, chkZFMQT }, personHistory, "kindredHistory.grandparent.grandparentiness.value", null, true);
		new ListPathCheckBinder()
				.bindCheckBitByBit(new Button[] { chkWZFMGXY, chkWZFMTNB, chkWZFMGXB, chkWZFMEXZL, chkWZFMGMZ, chkWZFMJSFL, chkWZFMNZZ, chkWZFMJHB, chkWZFMGY,
						chkWZFMXTJX, chkWZFMQT }, personHistory, "kindredHistory.materialGrandparent.materialGrandparentiness.value", null, true);
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkFQGXY, chkFQTNB, chkFQGXB, chkFQEXZL, chkFQGMZ, chkFQJSFL, chkFQNZZ, chkFQJHB, chkFQGY,
				chkFQXTJX, chkFQQT }, personHistory, "kindredHistory.father.fatheriness.value", null, true);
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkMQGXY, chkMQTNB, chkMQGXB, chkMQEXZL, chkMQGMZ, chkMQJSFL, chkMQNZZ, chkMQJHB, chkMQGY,
				chkMQXTJX, chkMQQT }, personHistory, "kindredHistory.mother.motheriness.value", null, true);
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkXDJMGXY, chkXDJMTNB, chkXDJMGXB, chkXDJMEXZL, chkXDJMGMZ, chkXDJMJSFL, chkXDJMNZZ,
				chkXDJMJHB, chkXDJMGY, chkXDJMXTJX, chkXDJMQT }, personHistory, "kindredHistory.sister.sisteriness.value", null, true);
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkZNGXY, chkZNTNB, chkZNGXB, chkZNEXZL, chkZNGMZ, chkZNJSFL, chkZNNZZ, chkZNJHB, chkZNGY,
				chkZNXTJX, chkZNQT }, personHistory, "kindredHistory.child.childiness.value", null, true);

		// 有无残疾
		new ListPathCheckBinder().bindCheckBitByBit(new Button[] { chkWCJ, chkTLCJ, chkYYCJ, chkZTCJ, chkZLCJ, chkJSCJ, chkQTCJ }, personHistory,
													"deformityHistorys.deformityHistory.value", null, true);
	}

	@Override
	protected void doPrint() {

	}

	@Override
	protected void doAdd() {
		// opState = OperationState.ADD;
		//		
		if(curTab == Tab.PERSON) {
			ap.updateUI(person, null);
			SuperContext.currentPerson = null;
		} else {
			// ap.updateUI(personHistory, null);

		}
		HealthRecordListenerRegister.getInstance().postEvent(null, EventType.REFRESH);
		// 要在后面调用，否则....postEvent(..)又会把民族弄回"请选择"
		if(curTab == Tab.PERSON) {
			selectHanZu();// 选汉族
			initPersonTabTime();
			refreshPersonTab();// 初始化时间框到当前时间
			//initHisTab();
			ap.updateModel();
		}
		switchView(PersonBaseInfoViewState.ADD_VIEW);
	}
	private void initPersonTabTime(){
		Control[] ctls = baseContainer.getChildren();
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		
		dtBirthday.setYear(year);
		dtBirthday.setMonth(month);
		dtBirthday.setDay(day);

		dtArchiveDate.setYear(year);
		dtArchiveDate.setMonth(month);
		dtArchiveDate.setDay(day);

		// 居委会
		CommonUtils.initDsGeography(cmbCommittee, treeObj);
		cmbArchiveUserId.setText(SuperContext.getCurrentUser().getUserName());
		cmbAdminUserId.setText(SuperContext.getCurrentUser().getUserName());
	}
	private void refreshPersonTab() {
		
		
		
		//职业
		DictCode dc = (DictCode) cmbOccupation.getData(cmbOccupation.getItem(cmbOccupation.getSelectionIndex()));
		if(dc.getCodeNum().equals("32")) {
			txtOccupationOther.setEnabled(true);
		} else {
			txtOccupationOther.setEnabled(false);
			txtOccupationOther.setText("");
		}
		
		//民族
		dc = (DictCode) cmbNationality.getData(cmbNationality.getItem(cmbNationality.getSelectionIndex()));
		if(dc.getCodeNum().equals("32")) {
			txtNationalityOther.setEnabled(true);
		} else {
			txtNationalityOther.setEnabled(false);
			txtNationalityOther.setText("");
		}
	}

	private void initHisTabTime(){
		DateTime[] dts = new DateTime[] { dtQZSZ1, dtQZSZ2, dtQZSZ3, dtQZSZ4, dtSSSJ1, dtSSSJ2, dtWSSJ1, dtWSSJ2, dtSXSJ1, dtSXSJ2, dtRYSJ1, dtCYSJ1, dtRYSJ2,
				dtCYSJ2, dtRYSJ3, dtCYSJ3, dtJLRQ };
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		for(DateTime dt : dts) {
			dt.setYear(year);
			dt.setMonth(month);
			dt.setDay(day);
		}
	}
	private void refreshHisTab() {
		
		// ControlsCascader.comboCascade(comboSS, new Control[] { dtSSSJ1,
		// dtSSSJ2, txtSSMC1, txtSSMC2 }, "codeNum", "1", true);
		Control[] sss = new Control[] { dtSSSJ1, dtSSSJ2, txtSSMC1, txtSSMC2 };
		DictCode dc = (DictCode) comboSS.getData(comboSS.getItem(comboSS.getSelectionIndex()));
		for(Control ss : sss) {
			ControlsCascader.triger(comboSS, ss, "codeNum", "1", true);
//			if(dc.getCodeNum().equals("1")) {
//				ss.setEnabled(true);
//			} else {
//				ss.setEnabled(false);
//				if(ss.getClass().equals(Text.class))
//					((Text) ss).setText("");
//			}
		}
		// ControlsCascader.comboCascade(comboWS, new Control[] { dtWSSJ1,
		// dtWSSJ2, txtWSMC1, txtWSMC2 }, "codeNum", "1", true);
		Control[] wss = new Control[] { dtWSSJ1, dtWSSJ2, txtWSMC1, txtWSMC2 };
		dc = (DictCode) comboWS.getData(comboWS.getItem(comboWS.getSelectionIndex()));
		for(Control ss : wss) {
			if(dc.getCodeNum().equals("1")) {
				ss.setEnabled(true);
			} else {
				ss.setEnabled(false);
				if(ss.getClass().equals(Text.class))
					((Text) ss).setText("");
			}
		}

		// ControlsCascader.comboCascade(comboSX, new Control[] { dtSXSJ1,
		// dtSXSJ2, txtSXYY1, txtSXYY2 }, "codeNum", "1", true);
		Control[] sxs = new Control[] { dtSXSJ1, dtSXSJ2, txtSXYY1, txtSXYY2 };
		dc = (DictCode) comboSX.getData(comboSX.getItem(comboSX.getSelectionIndex()));
		for(Control ss : sxs) {
			if(dc.getCodeNum().equals("1")) {
				ss.setEnabled(true);
			} else {
				ss.setEnabled(false);
				if(ss.getClass().equals(Text.class))
					((Text) ss).setText("");
			}
		}

		// ControlsCascader.comboCascade(comboZY, new Control[] { txtZYYY1,
		// txtZYYY2, txtZYYY3, dtRYSJ1, dtRYSJ2, dtRYSJ3, dtCYSJ1, dtCYSJ2,
		// dtCYSJ3, txtYLJGMC1,
		// txtYLJGMC2, txtYLJGMC3 }, "codeNum", "1", true);

		Control[] zys = new Control[] { txtZYYY1, txtZYYY2, txtZYYY3, dtRYSJ1, dtRYSJ2, dtRYSJ3, dtCYSJ1, dtCYSJ2, dtCYSJ3, txtYLJGMC1, txtYLJGMC2, txtYLJGMC3 };
		dc = (DictCode) comboZY.getData(comboZY.getItem(comboZY.getSelectionIndex()));
		for(Control ss : zys) {
			if(dc.getCodeNum().equals("1")) {
				ss.setEnabled(true);
			} else {
				ss.setEnabled(false);
				if(ss.getClass().equals(Text.class))
					((Text) ss).setText("");
			}
		}

		// ControlsCascader.comboCascade(cmbNXJJ, new Control[] { txtNXJJNL },
		// "codeNum", "101001", true);
		Control[] nxjjs = new Control[] { txtNXJJNL };
		dc = (DictCode) cmbNXJJ.getData(cmbNXJJ.getItem(cmbNXJJ.getSelectionIndex()));
		for(Control ss : nxjjs) {
			if(dc.getCodeNum().equals("101001")) {
				ss.setEnabled(true);
			} else {
				ss.setEnabled(false);
				if(ss.getClass().equals(Text.class))
					((Text) ss).setText("");
			}
		}

		// 家族史其他
		// new CheckboxBindingUtil().bindTextState(chkZFMQT, txtZFMQT, true);
		if(chkZFMQT.getSelection())
			txtZFMQT.setEnabled(true);
		else {
			txtZFMQT.setEnabled(false);
			txtZFMQT.setText("");
		}
		// new CheckboxBindingUtil().bindTextState(chkWZFMQT, txtWZFMQT, true);
		if(chkWZFMQT.getSelection())
			txtWZFMQT.setEnabled(true);
		else {
			txtWZFMQT.setEnabled(false);
			txtWZFMQT.setText("");
		}
		// new CheckboxBindingUtil().bindTextState(chkFQQT, txtFQQT, true);
		if(chkFQQT.getSelection())
			txtFQQT.setEnabled(true);
		else {
			txtFQQT.setEnabled(false);
			txtFQQT.setText("");
		}
		// new CheckboxBindingUtil().bindTextState(chkMQQT, txtMQQT, true);
		if(chkMQQT.getSelection())
			txtMQQT.setEnabled(true);
		else {
			txtMQQT.setEnabled(false);
			txtMQQT.setText("");
		}
		// new CheckboxBindingUtil().bindTextState(chkXDJMQT, txtXDJMQT, true);
		if(chkXDJMQT.getSelection())
			txtXDJMQT.setEnabled(true);
		else {
			txtXDJMQT.setEnabled(false);
			txtXDJMQT.setText("");
		}
		// new CheckboxBindingUtil().bindTextState(chkZNQT, txtZNQT, true);
		if(chkZNQT.getSelection())
			txtZNQT.setEnabled(true);
		else {
			txtXDJMQT.setEnabled(false);
			txtXDJMQT.setText("");
		}

		// 遗传病史
		// ControlsCascader.comboCascade(cmbYCBSYW, new Control[] { txtJBMC },
		// "codeNum", "1", true);
		Control[] ycbs = new Control[] { txtZYYY1, txtZYYY2, txtZYYY3, dtRYSJ1, dtRYSJ2, dtRYSJ3, dtCYSJ1, dtCYSJ2, dtCYSJ3, txtYLJGMC1, txtYLJGMC2, txtYLJGMC3 };
		dc = (DictCode) cmbYCBSYW.getData(cmbYCBSYW.getItem(cmbYCBSYW.getSelectionIndex()));
		for(Control ss : ycbs) {
			if(dc.getCodeNum().equals("1")) {
				ss.setEnabled(true);
			} else {
				ss.setEnabled(false);
				if(ss.getClass().equals(Text.class))
					((Text) ss).setText("");
			}
		}
		// 残疾有无互斥
		// mutexDeformity();
		final Button[] chks = new Button[] { chkTLCJ, chkYYCJ, chkZTCJ, chkZLCJ, chkJSCJ, chkQTCJ };

		if(chkWCJ.getSelection()) {
			for(Button b : chks) {
				b.setSelection(false);
				txtQTCJ.setText("");
				txtQTCJ.setEnabled(false);
			}
		}

		for(final Button b : chks) {
			if(b.getSelection()) {
				chkWCJ.setSelection(false);

			}
		}

		// 残疾其他
		// new CheckboxBindingUtil().bindTextState(chkQTCJ, txtQTCJ, true);
		if(chkQTCJ.getSelection())
			txtQTCJ.setEnabled(true);
		else {
			txtQTCJ.setEnabled(false);
			txtQTCJ.setText("");
		}
	}

	@Override
	protected void doDel() {
		try {
			// if(MessageDialog.openQuestion(null, "确认", "您确认删除该条信息吗？")) {
			if(DialogManager.invokeConfirmDlg("您确认删除该条信息吗？")) {
				if(curTab == Tab.PERSON) {
					DataSource.hrPersonService.delete(person);
					ap.updateUI(person, null);

				} else {
					DataSource.personHistoryService.delete(curHistory);
					ap.updateUI(curHistory, null);
				}
				switchView(PersonBaseInfoViewState.SHOW_VIEW);
			} else {
				return;
			}
		}
		catch(Throwable t) {
			t.printStackTrace();
		}
		// MessageDialog.openInformation(null, "", "成功删除所选信息！");
		DialogManager.invokeInfoDlg("成功删除所选信息！");
	}

	@Override
	protected void doEdit() {
		switchView(PersonBaseInfoViewState.EDIT_VIEW);
	}

	@Override
	public void setFocus() {
		closeOtherView();
	}

	@Override
	protected void doCancel() {
		switchView(PersonBaseInfoViewState.SHOW_VIEW);
	}

	@Override
	protected void doSave() {
		try {
			// 校验
			if(curTab == Tab.PERSON) {// 个人基本信息
				String err = validatePerson();
				if(err.length() > 0) {
					DialogManager.invokeTitleDig(err);
					return;
				}
			} else {// 健康史

			}

			ap.updateModel();// 强制更新一下模型, 对ComboBind暂不起作用

			// 保存个人基本信息
			if(person.getId() == null || person.getId() == 0) {
				person.setId(CustomGenerator.generator());
			}
			person.setCommonPojo(CommonUtils.getCommonPojo());
			Calendar c = Calendar.getInstance();
			if(DataSource.hrPersonService.getHrPerson(person.getId()) != null) {
				person.getCommonPojo().setUpdateTime(c.getTime());
				DataSource.hrPersonService.update(person);
			} else {
				DataSource.hrPersonService.save(person);
			}

			// 保存健康史
			if(curHistory.getId() == null || curHistory.getId() == 0) {
				curHistory.setId(CustomGenerator.generator());
			}
			curHistory.setCommonPojo(CommonUtils.getCommonPojo());
			curHistory.setContent(PojoXMLUtil.pojoToXML(personHistory));
			if(getPersonHistory(person.getId()) != null) {
				curHistory.getCommonPojo().setUpdateTime(c.getTime());
				DataSource.personHistoryService.update(curHistory);
			} else {
				curHistory.setId(CustomGenerator.generator());
				curHistory.setPersonId(person.getId());
				DataSource.personHistoryService.save(curHistory);
			}

			DialogManager.invokeInfoDlg("信息保存成功！");

			// if(this.viewstate == PersonBaseInfoViewState.ADD_VIEW) {// 若新增
			// if(curTab == Tab.PERSON) {
			// if(person.getId()==null || person.getId() == 0){
			// person.setId(CustomGenerator.generator());
			// }
			// person.setCommonPojo(CommonUtils.getCommonPojo());
			// if(DataSource.hrPersonService.save(person)){
			// curHistory.setContent(PojoXMLUtil.pojoToXML(personHistory));
			// curHistory.setCommonPojo(CommonUtils.getCommonPojo());
			// curHistory.setId(CustomGenerator.generator());
			// DataSource.personHistoryService.save(curHistory);
			// }
			// } else {
			// try{
			// if(DataSource.hrPersonService.getHrPerson(person.getId()) ==
			// null){
			//							
			// }
			// curHistory.setContent(PojoXMLUtil.pojoToXML(personHistory));
			// curHistory.setCommonPojo(CommonUtils.getCommonPojo());
			// curHistory.setId(CustomGenerator.generator());
			// DataSource.personHistoryService.update(curHistory);
			//					
			// }catch(Throwable t){
			// t.printStackTrace();
			// }
			// }
			//				
			// DialogManager.invokeInfoDlg("信息添加成功！");
			// } else {// 若修改
			// Calendar c = Calendar.getInstance();
			// person.setCommonPojo(CommonUtils.getCommonPojo());
			// person.getCommonPojo().setUpdateTime(c.getTime());
			//				
			//				
			//				
			// if(DataSource.hrPersonService.update(person)) {
			// PersonHistory ps = getPersonHistory(person.getId());
			// if(ps != null){
			// curHistory.setContent(PojoXMLUtil.pojoToXML(personHistory));
			// curHistory.setCommonPojo(CommonUtils.getCommonPojo());
			// curHistory.getCommonPojo().setUpdateTime(c.getTime());
			// curHistory.setPersonId(curPersonIDofHisTab);
			// DataSource.personHistoryService.update(curHistory);
			// }else{
			// curHistory.setContent(PojoXMLUtil.pojoToXML(personHistory));
			// curHistory.setCommonPojo(CommonUtils.getCommonPojo());
			// curHistory.setId(CustomGenerator.generator());
			// DataSource.personHistoryService.save(curHistory);
			// }
			// }
			// //MessageDialog.openInformation(null, "", "信息修改成功！");
			// DialogManager.invokeInfoDlg("信息修改成功！");
			// // }
			// }
			switchView(PersonBaseInfoViewState.SHOW_VIEW);
			curHisViewState = PersonBaseInfoViewState.SHOW_VIEW;
			curPersonViewState = PersonBaseInfoViewState.SHOW_VIEW;

		}
		catch(Throwable t) {
			t.printStackTrace();
		}

	}

	private String validatePerson() {
		String messgae = validateUtil.getMessage().toString();

		Geography geography = (Geography) cmbCommittee.getTreeItemData();

		if(geography != null && !geography.getfTreebh().equals("0")) {
			person.setHamlet(Long.valueOf(geography.getfTreebh()));
		}
		if(geography == null || geography.getfTreebh().equals("0"))
			messgae += (validateUtil.getListMessage().size() + 1) + "、请选择居委会！";
		if(messgae != null && messgae.trim().length() > 0) {
			return messgae;
		} else
			return "";

	}

	public void choosePerson() {
		try {
			HrPerson query = new HrPerson();
			// query.setName(person.getName());
			query.setName("");// 暂时不过滤
			List<HrPerson> hrPersonList = DataSource.hrPersonService.findPageInfoHrPerson(query, null);

			if(hrPersonList != null && hrPersonList.size() > 0) {
				HrPerson selectPerson;
				HrPersonMemberSelectDlg dlg = new HrPersonMemberSelectDlg(getViewSite().getShell(), hrPersonList);
				Object o = dlg.open();
				if(o != null) {
					selectPerson = (HrPerson) o;
					ap.updateUI(person, selectPerson);
					CommonUtils.selectGeography(this.cmbCommittee, person.getHamlet());
					switchView(PersonBaseInfoViewState.SHOW_VIEW);
					SuperContext.currentPerson = selectPerson;
					HealthRecordListenerRegister.getInstance().postEvent(selectPerson, EventType.REFRESH);
					refreshPersonTab();
				}
			} else {
				if(DialogManager.invokeConfirmDlg(person.getName() + Messages.getString("HrPersonAddInfo.0"))) {
					QuackAddPersonDialog addPersonDialog = new QuackAddPersonDialog(person, getSite().getShell(), SWT.NONE);
					HrPerson t = (HrPerson) addPersonDialog.open();
					if(t != null) {
						ap.updateUI(person, t);
						CommonUtils.selectGeography(this.cmbCommittee, person.getHamlet());
						refreshPersonTab();
					}
				}
			}
			cascadeMZOther();
			cascadeZYOther();
			ap.updateModel();
		}
		catch(Exception e) {
			DialogManager.invokeWarnDlg(e.getLocalizedMessage());
		}

	}

	private void cascadeZYOther() {
		if(cmbOccupation.getItem(cmbOccupation.getSelectionIndex()).equals("其他")) {
			txtOccupationOther.setEnabled(true);
		} else {
			txtOccupationOther.setEnabled(false);
		}

	}

	protected void setActionControl() {
		if(curTab == Tab.PERSON) {
			super.setActionControl();
			return;
		}
		if(viewstate == PersonBaseInfoViewState.ADD_VIEW || viewstate == PersonBaseInfoViewState.EDIT_VIEW) {
			toolItemAdd.setEnabled(false);// 新增
			toolItemEdit.setEnabled(false);// 编辑
			toolItemDel.setEnabled(false);// 删除
			toolItemCancel.setEnabled(true);// 取消
			toolItemSave.setEnabled(true);// 保存

		} else if(viewstate == PersonBaseInfoViewState.SHOW_VIEW) {
			toolItemAdd.setEnabled(false);//
			toolItemEdit.setEnabled(true);//
			toolItemDel.setEnabled(true);//
			toolItemCancel.setEnabled(false);//
			toolItemSave.setEnabled(false);//

		}

	}

	protected void switchView(PersonBaseInfoViewState state) {
		viewstate = state;
		setActionControl();

	}

	private boolean validate() {
		// TODO Auto-generated method stub
		return true;
	}

	protected void initCombo() {
		super.initCombo();
		CommonUtils.initUserCombo(this.cmbAdminUserId, SuperContext.getCurrentUser().getUserName(), true);
		CommonUtils.initJDUnitCombo(this.cmbArchiveOrgId, null, false);
		CommonUtils.initUserCombo(this.cmbArchiveUserId,  SuperContext.getCurrentUser().getUserName(), true);

		CommonUtils.initCombo(this.cmbBloodType, "BLOOD");
		CommonUtils.initCombo(this.cmbEducate, "WHCD");
		CommonUtils.initCombo(this.cmbMarried, "MARRY");

		CommonUtils.initCombo(this.cmbNationality, "MZ","汉族");
		TextCascade.cascade(cmbNationality, txtNationalityOther, "codeNum", "2", true);
		//		
		// cmbNationality.addSelectionListener(new SelectionAdapter() {//
		// 选择少数民族时后面文本框可用
		// @Override
		// public void widgetSelected(SelectionEvent e) {
		// cascadeMZOther();
		// }
		// });
		CommonUtils.initCombo(this.cmbOccupation, "ZHIYE");
		TextCascade.cascade(cmbOccupation, txtOccupationOther, "codeNum", "32", true);
		// cmbOccupation.addSelectionListener(new SelectionAdapter() {//
		// 选择其他时后面文本框可用
		// @Override
		// public void widgetSelected(SelectionEvent e) {
		// cascadeZYOther();
		// }
		// });
		CommonUtils.initCombo(this.cmbPayTypeId, "PAYTYPE");

		CommonUtils.initCombo(this.cmbSex, "SEX");
		// 手术
		CommonUtils.initCombo(this.comboSS, "YOUWU");
		// 外伤有无
		CommonUtils.initCombo(this.comboWS, "YOUWU");
		// 输血有无
		CommonUtils.initCombo(this.comboSX, "YOUWU");
		// 住院有无
		CommonUtils.initCombo(this.comboZY, "YOUWU");
		// 转归
		CommonUtils.initCombo(this.comboZGQG1, "ZGQK");
		CommonUtils.initCombo(this.comboZGQG2, "ZGQK");
		CommonUtils.initCombo(this.comboZGQG3, "ZGQK");
		CommonUtils.initCombo(this.comboZGQG4, "ZGQK");
		// 避孕方式
		CommonUtils.initCombo(this.cmbNXBBFY, "BYFS");
		// 绝经是否
		CommonUtils.initCombo(this.cmbNXJJ, "YES_NO");

		// 遗传病史有无
		CommonUtils.initCombo(this.cmbYCBSYW, "YOUWU");
		// 病史页责任医生
		CommonUtils.initUserCombo(this.cmbZRYS, null, true);
	}

	private void cascadeMZOther() {
		if(cmbNationality.getItem(cmbNationality.getSelectionIndex()).equals("少数民族")) {
			txtNationalityOther.setEnabled(true);
		} else {
			txtNationalityOther.setEnabled(false);
		}

	}

	private void selectHanZu() {
		for(int i = 0; i < cmbNationality.getItemCount(); i++) {// 默认选汉族
			DictCode dc = (DictCode) cmbNationality.getData(cmbNationality.getItem(i));
			if(dc.getCodeNum().equals("1")) {
				cmbNationality.select(i);
				break;
			}

		}

	}

	@Override
	protected void addlistener() {
		// TODO Auto-generated method stub
		super.addlistener();
		tabFolder.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					if(tabFolder.getSelectionIndex() == 1) {
						if(person.getId() == null || person.getId() == 0) {
							person.setId(CustomGenerator.generator());
							//							
						}
						String err = validatePerson();// 验证个人基本信息
						if(err.length() > 0) {
							tabFolder.setSelection(0);
							DialogManager.invokeWarnDlg("当前个人基本信息存在如下错误,切换前必须改正：\r\n" + err);
							return;
						}
						if(person.getSex() == 1L) {// 男性，则隐藏女性病史
							sectWoman.setEnabled(false);
							sectWoman.setExpanded(false);

						} else {
							sectWoman.setEnabled(true);
							sectWoman.setExpanded(true);

						}
						
						curTab = Tab.HISTORY;// 记录当前所处页面，保存时会用
						curPersonViewState = viewstate;// 记录个人基本信息页面最后状态
						if(!curPersonIDofHisTab.equals(person.getId())) {
							curHistory = getPersonHistory(person.getId());
							if(curHistory != null) {
								switchView(PersonBaseInfoViewState.SHOW_VIEW);// 若存在病史信息则转入编辑状态
							} else {
								curHistory = new PersonHistory();
								curHistory.setPersonId(person.getId());
								switchView(PersonBaseInfoViewState.ADD_VIEW);// 否则为填加状态
							}
							String xml = curHistory.getContent();
							PersonHistoryXMLPojo ps = null;
							if(xml != null && xml.trim().length() > 0)
								ps = (PersonHistoryXMLPojo) PojoXMLUtil.XMLToPojo(xml, PersonHistoryXMLPojo.class);
							ap.updateUI(personHistory, ps);
							curPersonIDofHisTab = person.getId();

						} else {// 若两个页面的personid配置，则不读数据库，且直接切换到上次已保存的viewstate
							switchView(curHisViewState);
						}
						
						if(viewstate == PersonBaseInfoViewState.ADD_VIEW){
							initHisTabTime();
							
						}
						refreshHisTab();
						// }
					} else {
						curTab = Tab.PERSON;
						switchView(curPersonViewState);
						curHisViewState = viewstate;// 记住病史页面当前状态
					}
				}
				catch(Throwable t) {
					t.printStackTrace();
				}
			}

		});

		txtNXCCNL.addVerifyListener(new TextVerifyListener(1));
		txtYJZQ.addVerifyListener(new TextVerifyListener(1));
		txtXJTS.addVerifyListener(new TextVerifyListener(1));
		txtNXJJNL.addVerifyListener(new TextVerifyListener(1));
		txtNXRCCS.addVerifyListener(new TextVerifyListener(1));
		txtNXSYCS.addVerifyListener(new TextVerifyListener(1));

		txtNXPGCCS.addVerifyListener(new TextVerifyListener(1));
		txtNXZRLCCS.addVerifyListener(new TextVerifyListener(1));
		txtNXRGLCCS.addVerifyListener(new TextVerifyListener(1));

	}

	private PersonHistory getPersonHistory(Long id) {
		try {
			PersonHistory ps = new PersonHistory();
			ps.setPersonId(id);
			List<PersonHistory> list = null;
			try {
				list = DataSource.personHistoryService.findPageInfoPersonHistory(ps, null);
			}
			catch(Throwable t) {
				t.printStackTrace();
			}
			if(list != null && list.size() > 0) {
				return list.get(0);
			} else {
				return null;
			}
		}
		catch(Throwable t) {
			t.printStackTrace();
			return null;
		}
	}

	public void propertyChange(PropertyChangeEvent event) {
		if(event.getProperty().equals(EventType.REFRESH)) {
			ap.updateUI(person, SuperContext.currentPerson);
			switchView(PersonBaseInfoViewState.SHOW_VIEW);
			// opState = OperationState.EDIT;
		}

	}

	public void closeOtherView(){		
		ViewUitl.closeView(YearCheckView.ID);
		ViewUitl.closeView(ChildRenRegisterView.ID);
		ViewUitl.closeView(InfantHealthView.ID);
		ViewUitl.closeView(ChildrenCheckView.ID);
		ViewUitl.closeView(PregnantRecordView.ID);
		ViewUitl.closeView(AntenatalreView.ID);
		ViewUitl.closeView(PostpartumView.ID);
		ViewUitl.closeView(Postpartum42DayCheckView.ID);
		
		ViewUitl.closeView(DiabetesVisitsView.ID);
		ViewUitl.closeView(SchizophreniaVisitsView.ID);
	
		ViewUitl.closeView(HypertensionVisitView.ID);
		ViewUitl.closeView(TuberculosisVisits1View.ID);
	}
	

}
